package com.yeqiangwei.commons.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * 
 * @author Hongguang
 *
 */
public class ParamHelper {
	
	private static final Log LOG = LogFactory.getLog(ParamHelper.class);
	
	public static final Long getLong(HttpServletRequest request
			, String name, Long defaultVal) {
		String val = getString(request, name, null);
		if(ValidatorHelper.isEmpty(val)) {
			return defaultVal;
		}
		try {
			return Long.parseLong(val);
		} catch (Exception e) {
			LOG.error("Failed to get parameter for " + name + ", val = " + val);
			LOG.error(e);
			return defaultVal;
		}
	}
	
	public static final Integer getInteger(HttpServletRequest request
			, String name, Integer defaultVal) {
		String val = getString(request, name, null);
		if(ValidatorHelper.isEmpty(val)) {
			return defaultVal;
		}
		try {
			return Integer.parseInt(val);
		} catch (Exception e) {
			LOG.error(e);
			return defaultVal;
		}
	}

	public static final String getString(HttpServletRequest request
			, String name, String defaultVal) {
		if(request == null || name == null) {
			return defaultVal;
		}
		String val = request.getParameter(name);
		if(val == null) {
			return defaultVal;
		} else {
			return val;
		}
	}
	
	public static final Boolean getBoolean(HttpServletRequest request
			, String name, Boolean defaultVal) {
		String val = getString(request, name, null);
		if(ValidatorHelper.isEmpty(val)) {
			return defaultVal;
		}
		else if(val.equalsIgnoreCase("true")
				|| val.equalsIgnoreCase("1")) {
			return true;
		} else {
			return false;
		}
	}
}
